
import React, { Component } from 'react'
import { fetchData } from '../AjaxConsumer'
import { Select } from 'antd';
const Option = Select.Option;

export default class SelectUrl extends Component {
  constructor(props) {
    super(props);
    const value = this.props.value || '';
    this.state = {
      optionList: [],
      type: this.props.type,
      currency: value || '',
    };
  }
  componentWillReceiveProps(nextProps) {
    // Should be a controlled component.
    if ('value' in nextProps) {
      const value = nextProps.value;
      this.setState({ currency: value });
    }
    if (nextProps.url != this.props.url) {
      this.getData(nextProps.url);
    }
  }
  handleCurrencyChange = (value) => {
    if (!('value' in this.props)) {
      this.setState({ currency: value });
    }
    // CascadeSelectUrl用的接口
    if (this.props.selectOnChange) {
      this.props.selectOnChange(value)
    }
    this.triggerChange(value);
  }
  triggerChange = (changedValue) => {
    // Should provide an event to pass value to Form.
    const onChange = this.props.onChange;
    if (onChange) {
      onChange(changedValue);
    }
  }
  //拉取数据
  getData = (url) => {
    if (url) {
      const option = {
        url: url,
        condition: {},
        type: this.state.type ? this.state.type : 'get',
      };
      fetchData(this, option, (res) => {
        this.setState({
          optionList: res.data
        })
      })
    } else {
      //若url传入为空，则清空数据列表
      this.clearOptionList();
    }
  }
  componentDidMount() {
    this.getData(this.props.url);
  }
  //重置下拉框
  clearOptionList = () => {
    this.setState({
      optionList: [],
      currency: ''
    })

  }
  render() {
    let optionList = this.state.optionList;
    const dicCode = this.props.dicCode;
    const dicName = this.props.dicName;
    const state = this.state;
    return (
      <Select
        placeholder="请选择"
        value={state.currency}
        onChange={this.handleCurrencyChange}
        allowClear
        disabled={this.props.isDisable}
        style={{ width: this.props.width }}
      >
        {optionList.map((ee, eIndex) => {
          return (
            <Option key={eIndex} value={ee[dicCode]}>{ee[dicName]}</Option>
          )
        })
        }
      </Select>
    );
  }
}
